<template>
  <el-card class="message-card" shadow="never">
    <div class="section-header">
      <h3 class="section-title">通知中心</h3>
      <div class="message-stats">
        <el-badge :value="unreadCount" class="unread-badge" type="primary">
          <span class="unread-text">未读消息</span>
        </el-badge>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="messages.length === 0" class="empty-messages">
      <el-empty description="暂无消息" />
    </div>
    
    <div v-else class="message-list">
      <el-collapse accordion>
        <el-collapse-item v-for="(message, index) in messages" :key="message.id">
          <template #title>
            <div class="message-item-header">
              <div class="message-title" :class="{ 'unread': !message.read }">
                <el-tag size="small" :type="message.read ? 'info' : 'primary'" effect="plain">
                  {{ message.read ? '已读' : '未读' }}
                </el-tag>
                <span class="title-text">{{ message.title }}</span>
              </div>
              <div class="message-date">{{ message.date }}</div>
            </div>
          </template>
          
          <div class="message-content">
            <p>{{ message.content }}</p>
            <div class="message-actions">
              <el-button 
                size="small" 
                plain
                :type="message.read ? 'info' : 'primary'"
                @click.stop="markAsRead(message)"
                :disabled="message.read"
                :loading="loadingStates.read === message.id"
              >
                <el-icon><Check /></el-icon>
                {{ message.read ? '已读' : '标记为已读' }}
              </el-button>
              <el-button 
                size="small" 
                plain
                type="danger" 
                @click.stop="deleteMessage(message)"
                :loading="loadingStates.delete === message.id"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    
    <div class="pagination-container" v-if="messages.length > 0">
      <el-pagination
        layout="prev, pager, next"
        :total="totalMessages"
        :page-size="pageSize"
        @current-change="handlePageChange"
        background
      />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Delete } from '@element-plus/icons-vue'
import { apiGetUserMessages, apiMarkMessageAsRead, apiDeleteMessage, apiGetUnreadMessageCount } from '@/api/api'

interface Message {
  id: number;
  title: string;
  content: string;
  date: string;
  read: boolean;
}

const messages = ref<Message[]>([]);
const loading = ref(true);
const unreadCount = ref(0);
const pageSize = 5;
const currentPage = ref(1);
const totalMessages = ref(0);
const loadingStates = ref({
  read: 0,
  delete: 0
});

// 获取消息列表
async function fetchMessages() {
  loading.value = true;
  try {
    const res:any = await apiGetUserMessages(currentPage.value, pageSize);
    if (res.code === 200) {
      messages.value = res.data.map((item: any) => ({
        ...item,
        read: item.read !== undefined ? item.read : item.isRead
      }));
      totalMessages.value = res.msg || 0;
    } else {
      ElMessage.error(res.msg || '获取消息失败');
    }
  } catch (error) {
    console.error('获取消息列表失败:', error);
    ElMessage.error('获取消息列表失败');
  } finally {
    loading.value = false;
  }
}

// 获取未读消息数量
async function fetchUnreadCount() {
  try {
    const res:any = await apiGetUnreadMessageCount();
    if (res.code === 200) {
      unreadCount.value = res.data;
    }
  } catch (error) {
    console.error('获取未读消息数量失败:', error);
  }
}

// 标记消息为已读
async function markAsRead(message: Message) {
  if (message.read) return;
  
  loadingStates.value.read = message.id;
  try {
    const res:any = await apiMarkMessageAsRead(message.id);
    if (res.code === 200) {
      message.read = true;
      ElMessage.success('已标记为已读');
      fetchUnreadCount(); // 更新未读消息数量
    } else {
      ElMessage.error(res.msg || '操作失败');
    }
  } catch (error) {
    console.error('标记已读失败:', error);
    ElMessage.error('标记已读失败');
  } finally {
    loadingStates.value.read = 0;
  }
}

// 删除消息
function deleteMessage(message: Message) {
  ElMessageBox.confirm(
    '确定要删除这条消息吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    loadingStates.value.delete = message.id;
    try {
      const res:any = await apiDeleteMessage(message.id);
      if (res.code === 200) {
        const index = messages.value.findIndex(m => m.id === message.id);
        if (index > -1) {
          messages.value.splice(index, 1);
          ElMessage.success('删除成功');
          
          // 如果删除后当前页没有数据且不是第一页，则返回上一页
          if (messages.value.length === 0 && currentPage.value > 1) {
            currentPage.value--;
            fetchMessages();
          }
          
          // 如果删除的是未读消息，更新未读消息数量
          if (!message.read) {
            fetchUnreadCount();
          }
        }
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除消息失败:', error);
      ElMessage.error('删除消息失败');
    } finally {
      loadingStates.value.delete = 0;
    }
  }).catch(() => {
    // 用户点击取消
  });
}

// 页码变化
function handlePageChange(page: number) {
  currentPage.value = page;
  fetchMessages();
}

// 组件挂载时获取数据
onMounted(() => {
  fetchMessages();
  fetchUnreadCount();
});
</script>

<style scoped>
.message-card {
  border: none;
  box-shadow: none !important;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  color: #303133;
  font-weight: 600;
  margin: 0;
}

.message-stats {
  display: flex;
  align-items: center;
}

.unread-badge {
  margin-left: 8px;
}

.unread-text {
  font-size: 14px;
  color: #606266;
}

.message-list {
  margin-bottom: 24px;
}

.message-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.message-title {
  display: flex;
  align-items: center;
  font-weight: normal;
}

.message-title.unread {
  font-weight: bold;
}

.title-text {
  margin-left: 12px;
}

.message-date {
  font-size: 13px;
  color: #909399;
}

.message-content {
  padding: 16px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  border-top: 1px solid #ebeef5;
}

.message-actions {
  display: flex;
  justify-content: flex-start;
  margin-top: 16px;
  gap: 12px;
}

.empty-messages {
  padding: 40px 0;
  display: flex;
  justify-content: center;
}

.loading-container {
  padding: 20px 0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}
</style> 